<?php
/*
 * Favorite a recipe.
 */

// authenticate user first
F3::call('authentication.php');
if (F3::exists('auth_error'))
{
  // authentication failed
  return;
}

if (!F3::exists('POST.user_id') || !F3::exists('POST.recipe_id')):
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Need both a user id and a recipe id.");
	echo json_encode($err);
	return;
endif;

// get user ID from session
$id = F3::get('SESSION.user_id');
if($id!=F3::get('POST.user_id')):
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Given user id does not match authenticated user.");
	echo json_encode($err);
	return;
endif;

// does recipe exist?
$rid = F3::get('POST.recipe_id');
$param = array('1'=>$rid);
$result = DB::sql("SELECT rid from recipes where rid = ?", $param);
if(count($result)==0):
	//the recipe doesn't exist
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Recipe does not exist.");
	echo json_encode($err);
	return;
endif;

// favorite recipe
$param = array('1'=>$id, '2'=>$rid);
DB::sql("insert into favorites(uid, rid, timestamp) values (?, ?, now())",$param);

// success
header('HTTP/1.1 204');
header("Content-Type: application/json");
$response = "success";
echo json_encode($response);
return;
?>
